import {
  defineComponent,
  h,
  PropType,
  reactive,
  resolveComponent,
  VNode,
} from 'vue';
import { useController, useNamespace } from '@ibiz-template/vue3-util';
import { EventBase } from '@ibiz-template/runtime';
import { FormMDCtrlDataViewController } from './form-mdctrl-data-view.controller';
import FormMDCtrlContainer from '../form-mdctrl-container/form-mdctrl-container';

export const FormMDCtrlDataView = defineComponent({
  name: 'IBizFormMDCtrlDataView',
  props: {
    controller: {
      type: Object as PropType<FormMDCtrlDataViewController>,
      required: true,
    },
  },
  setup(props) {
    const ns = useNamespace('form-mdctrl');

    useController(props.controller);

    const c = props.controller;

    c.state = reactive(c.state);

    return { ns, c };
  },
  render() {
    const c = this.c;

    const renderContent = (): VNode | undefined => {
      if (c.controlModel && c.provider) {
        const tempContext = c.parent.form.context.clone();
        const controlProps = {
          modelData: c.controlModel,
          context: tempContext,
          params: c.parent.form.params,
          onSelectionChange: (arg: EventBase): void => c.onSelectionChange(arg),
          onMounted: (event: EventBase): void => c.onDataViewMounted(event),
          class: this.ns.b('form-content-control'),
        };

        const controlComponent = h(
          resolveComponent(c.provider.component),
          controlProps,
        );
        return (
          <div class={this.ns.b('form-content')}>
            {controlComponent}
            <div class={this.ns.b('btn')}>
              <el-button
                type='danger'
                class={this.ns.b('remove-btn')}
                disabled={!this.c.state.isSelect}
                onClick={(): void => this.c.onDataRemove()}
              >
                删除
              </el-button>
            </div>
          </div>
        );
      }
    };
    return (
      <FormMDCtrlContainer
        controller={c.parent}
        onInsertButtonClick={(): void => {
          c.onDataInsert();
        }}
      >
        {renderContent()}
      </FormMDCtrlContainer>
    );
  },
});

export default FormMDCtrlDataView;
